﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace Telmex
{
    /// <summary>
    /// Extension methods for <see cref="System.Net.HttpWebRequest"/>.
    /// </summary>
    public static class HttpWebRequestExtensions
    {
        /// <summary>
        /// Does a POST with the given parameters.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static HttpWebResponse Post(this HttpWebRequest request, IDictionary<string,string> parameters)
        {
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";

            ASCIIEncoding encoding = new ASCIIEncoding();

            StringBuilder postData = new StringBuilder();
            foreach (var parameter in parameters)
            {
                postData = postData.Append(String.Concat(parameter.Key, "=", parameter.Value, "&"));
            }
            postData.Remove(postData.Length - 1, 1);         
            byte[] rawData = encoding.GetBytes(postData.ToString());

            request.ContentLength = rawData.Length;
            Stream stream = request.GetRequestStream();
            stream.Write(rawData, 0, rawData.Length);
            stream.Close();
            stream.Dispose();

           return request.GetResponse() as HttpWebResponse;
        }
    }
}
